package com.nep.NEPM.controller;

import com.nep.NEPM.utils.ViewUtils;
import com.nep.entity.administrator.User;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ConfirmAQIListViewController {
    @FXML
    private Button btn_OUT;
    @FXML
    private Button btn_SupervisorList;
    @FXML
    private Button btn_ConfirmAQIlist;
    @FXML
    private Button btn_ProvinceGro;
    @FXML
    private Button btn_AQIDistributeTotalStatis;
    @FXML
    private Button btn_AQITrend;
    @FXML
    private Button btn_Others;

    public void OUT(ActionEvent actionEvent) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/IndexView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_OUT.getScene();
        scene.setRoot(root);
    }

    public void SupervisorList() throws IOException {
        Parent root = ViewUtils.loadView("../view/SupervisorListView.fxml");
        Stage stage = (Stage) btn_SupervisorList.getScene().getWindow();
        Scene scene = btn_SupervisorList.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }

    public void ConfirmAQIList() throws IOException {
        Parent root = ViewUtils.loadView("../view/ConfirmAQIListView.fxml");
        Stage stage = (Stage) btn_ConfirmAQIlist.getScene().getWindow();
        Scene scene = btn_ConfirmAQIlist.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }

    public void ProvinceGro() throws IOException {
        Parent root = ViewUtils.loadView("../view/ProvinceGroView.fxml");
        Stage stage = (Stage) btn_ProvinceGro.getScene().getWindow();
        Scene scene = btn_ProvinceGro.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }

    public void AQIDistributeTotalStatis() throws IOException {
        Parent root = ViewUtils.loadView("../view/AQIDistributeTotalStatis.fxml");
        Stage stage = (Stage) btn_AQIDistributeTotalStatis.getScene().getWindow();
        Scene scene = btn_AQIDistributeTotalStatis.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }

    public void AQITrend() throws IOException {
        Parent root = ViewUtils.loadView("../view/AQITrendView.fxml");
        Stage stage = (Stage) btn_AQITrend.getScene().getWindow();
        Scene scene = btn_AQITrend.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }

    public void Others() throws IOException {
        Parent root = ViewUtils.loadView("../view/OthersView.fxml");
        Stage stage = (Stage) btn_Others.getScene().getWindow();
        Scene scene = btn_Others.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }

    @FXML
    private ComboBox<String> cmbProvince, cmbCity;
    @FXML
    private DatePicker datePicker;
    @FXML
    private TableColumn<User, String> colId;
    @FXML
    private TableColumn<User, String> colName;
    @FXML
    private TableColumn<User, String> colProvince;
    @FXML
    private TableColumn<User, String> colCity;
    @FXML
    private TableColumn<User, String> colGrade;
    @FXML
    private TableColumn<User, String> colDate;
    @FXML
    private TableColumn<User, String> colTime;
    @FXML
    private TableColumn<User, Void> colDetail;
    @FXML
    private TableColumn<User, Void> colGridName;
    @FXML
    private TableView<User> tableView;

    private Map<String, List<String>> provinceMap = new HashMap<>();
    private Map<String, List<String>> cityMap = new HashMap<>();

    private ObservableList<User> userList = FXCollections.observableArrayList(
            new User("39", "山西省", "太原市", "健康污染(三)", "2022-11-03", "11105/7", "关闭"),
            new User("37", "辽宁省", "大连市", "中度污染(四)", "2022-10-27", "17015/2", "待见"),
            new User("36", "浙江省", "杭州市", "重度污染(五)", "2022-08-26", "13292/5", "查维"),
            new User("35", "江苏省", "南京市", "轻度污染(六)", "2022-10-26", "13285/0", "查维"),
            new User("34", "辽宁省", "大连市", "严重污染(六)", "2022-09-26", "13280/9", "复信瑞"),
            new User("33", "辽宁省", "大连市", "中度污染(四)", "2022-07-26", "13261/4", "张江"),
            new User("32", "辽宁省", "沈阳市", "轻度污染(三)", "2022-06-26", "13245/8", "查维"),
            new User("31", "河南省", "郑州市", "中度污染(四)", "2022-04-26", "13232/0", "查维"),
            new User("30", "河南省", "郑州市", "重度污染(五)", "2022-07-26", "12521/8", "查维")
    );
    public void initialize() {
        tableView.setItems(userList);
        colId.setCellValueFactory(new PropertyValueFactory<>("id"));
        colName.setCellValueFactory(new PropertyValueFactory<>("name"));
        colProvince.setCellValueFactory(new PropertyValueFactory<>("province"));
        colCity.setCellValueFactory(new PropertyValueFactory<>("city"));
        colGrade.setCellValueFactory(new PropertyValueFactory<>("grade"));
        colDate.setCellValueFactory(new PropertyValueFactory<>("date"));
        colTime.setCellValueFactory(new PropertyValueFactory<>("time"));
        colGridName.setCellValueFactory(new PropertyValueFactory<>("gridName"));


        colDetail.setCellFactory(cols -> new TableCell<>() {
            private Button btn = new Button("详情");

            {
                btn.setOnAction(e -> {
                    try {
                        // 获取当前行的用户数据
                        User user = getTableView().getItems().get(getIndex());

                        Stage stage = new Stage();
                        FXMLLoader fxmlLoader = new FXMLLoader();
                        URL url = getClass().getResource("../view/ConfirmAQIContentView.fxml");
                        fxmlLoader.setLocation(url);
                        Parent root = fxmlLoader.load();

                        // 获取控制器并传递用户数据
                        ConfirmAQIContentViewController controller = fxmlLoader.getController();
                        controller.initData(user);

                        // 设置场景并显示窗口
                        Scene scene = new Scene(root);
                        stage.setScene(scene);
                        stage.setTitle("公众监督数据详情 - " + user.getName());
                        stage.show();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        // 可以添加错误提示对话框
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                        alert.setTitle("错误");
                        alert.setHeaderText("加载详情页面失败");
                        alert.setContentText(ex.getMessage());
                        alert.showAndWait();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty ? null : btn);
            }
        });
        provinceMap.put("安徽省", List.of("合肥", "芜湖", "淮南", "阜阳"));
        provinceMap.put("北京市", List.of("北京"));
        provinceMap.put("重庆市", List.of("重庆"));
        provinceMap.put("福建省", List.of("福州", "厦门", "莆田", "泉州"));
        provinceMap.put("甘肃省", List.of("兰州")); // 注：西宁属青海省，此处按用户原分类调整
        provinceMap.put("广东省", List.of("广州", "深圳", "东莞", "佛山", "惠州", "汕头", "珠海", "江门", "湛江"));
        provinceMap.put("广西壮族自治区", List.of("南宁", "柳州", "桂林"));
        provinceMap.put("贵州省", List.of("贵阳"));
        provinceMap.put("海南省", List.of("海口"));
        provinceMap.put("河北省", List.of("石家庄", "唐山", "廊坊", "大同", "秦皇岛", "张家口", "邢台", "保定"));
        provinceMap.put("河南省", List.of("郑州", "洛阳", "开封", "新乡", "南阳"));
        provinceMap.put("黑龙江省", List.of("哈尔滨", "齐齐哈尔", "大庆"));
        provinceMap.put("湖北省", List.of("武汉", "襄阳", "宜昌"));
        provinceMap.put("湖南省", List.of("长沙", "岳阳", "衡阳", "株洲"));
        provinceMap.put("吉林省", List.of("长春", "吉林", "大庆"));
        provinceMap.put("江苏省", List.of("南京", "苏州", "无锡", "南通", "徐州", "盐城", "扬州", "常州"));
        provinceMap.put("江西省", List.of("南昌", "赣州", "上饶"));
        provinceMap.put("辽宁省", List.of("沈阳", "大连", "鞍山", "抚顺", "锦州", "营口"));
        provinceMap.put("内蒙古自治区", List.of("呼和浩特", "包头", "赤峰"));
        provinceMap.put("宁夏回族自治区", List.of("银川"));
        provinceMap.put("山东省", List.of("济南", "青岛", "淄博", "烟台", "临沂", "济宁", "泰安", "潍坊"));
        provinceMap.put("山西省", List.of("太原", "大同", "长治"));
        provinceMap.put("陕西省", List.of("西安", "咸阳"));
        provinceMap.put("上海市", List.of("上海"));
        provinceMap.put("四川省", List.of("成都", "绵阳", "泸州", "宜宾", "南充"));
        provinceMap.put("天津市", List.of("天津"));
        provinceMap.put("新疆维吾尔自治区", List.of("乌鲁木齐"));
        provinceMap.put("西藏自治区", List.of("拉萨"));
        provinceMap.put("云南省", List.of("昆明"));
        provinceMap.put("浙江省", List.of("杭州", "宁波", "温州", "绍兴", "台州", "义乌", "慈溪"));
        provinceMap.put("青海省", List.of("西宁"));
        cmbProvince.setItems(FXCollections.observableArrayList(provinceMap.keySet()));
        cmbProvince.getSelectionModel().clearSelection();
        cmbProvince.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
                List<String> citys = provinceMap.getOrDefault(newValue, List.of());
                cmbCity.setItems(FXCollections.observableArrayList(citys));
                cmbCity.getSelectionModel().clearSelection();
            }
        });
        datePicker.setValue(LocalDate.now());
        //添加监听时间，处理选择的时间
        datePicker.valueProperty().addListener(new ChangeListener<LocalDate>() {
            @Override
            public void changed(ObservableValue<? extends LocalDate> observableValue, LocalDate oldDate, LocalDate newDate) {
                System.out.println("选择的日期为：" + newDate);
            }
        });
    }
    @FXML
    private void clearFilters() {
        cmbProvince.getSelectionModel().clearSelection();
        cmbCity.getSelectionModel().clearSelection();
        datePicker.setValue(null);
        tableView.setItems(userList);
    }

    @FXML
    private void search() {
        String province = cmbProvince.getValue();
        String city = cmbCity.getValue();
        LocalDate date = datePicker.getValue();

        ObservableList<User> filteredList = userList.stream()
                .filter(user -> province == null || user.getProvince().equals(province))
                .filter(user -> city == null || user.getCity().equals(city))
                .filter(user -> date == null || user.getDate().equals(date.toString()))
                .collect(Collectors.toCollection(FXCollections::observableArrayList));

        tableView.setItems(filteredList);
    }

}
